package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.strategy.SaveOrderStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Author  王东剑
 * Created on 23/6/2024 PM2:00
 * Package_name com.atguigu.tingshu.order.context
 * Description
 */
@Component
public class SaveOrderStrategyContext implements ApplicationContextAware {
	private static final Map<String, SaveOrderStrategy> saveOrderStrategyMap = new ConcurrentHashMap<>();

	public static SaveOrderStrategy getSaveOrderStrategy(String payWay) {
		return saveOrderStrategyMap.get(payWay);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// 获取 String 实例化完成的 SaveOrderStrategy 类型的对象集合
		Map<String, SaveOrderStrategy> beansOfType = applicationContext.getBeansOfType(SaveOrderStrategy.class);
		// 将集合数据以 key为payWay value为对应的bean 放入 saveOrderStrategyMap 这个 Map 中
		for (Map.Entry<String, SaveOrderStrategy> stringSaveOrderStrategyEntry : beansOfType.entrySet()) {
			SaveOrderStrategy saveOrderStrategy = stringSaveOrderStrategyEntry.getValue();
			saveOrderStrategyMap.put(saveOrderStrategy.getPayWay(), saveOrderStrategy);
		}
	}
}
